package com.example.bluetoothttss;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends AppCompatActivity implements View.OnClickListener {
    private Button register,login;
    private EditText username,password;
    private MySQLiteOpenHelper mySQLiteOpenHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mySQLiteOpenHelper = new MySQLiteOpenHelper(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        find();
    }

    public void find(){
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        username = findViewById(R.id.lusername);
        password = findViewById(R.id.lpassword);
        login.setOnClickListener(this);
        register.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();

        if (id == R.id.login) {
            String usernameInput = username.getText().toString();
            String passwordInput = password.getText().toString();

            if (usernameInput.isEmpty()) {
                Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            } else if (passwordInput.isEmpty()) {
                Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            } else {
                boolean isLoginSuccessful = mySQLiteOpenHelper.login(usernameInput, passwordInput);

                if (isLoginSuccessful) {
                    Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();

                    User selectedUser = mySQLiteOpenHelper.select(usernameInput);
                    Intent homeIntent = new Intent(Login.this, MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("username", selectedUser.username);
                    bundle.putString("emil", selectedUser.emil);
                    bundle.putString("phone", selectedUser.phone);
                    homeIntent.putExtras(bundle);

                    username.setText("");
                    password.setText("");

                    startActivity(homeIntent);
                } else {
                    Toast.makeText(this, "账号或密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                    password.setText("");
                }
            }
        }
        else if (id == R.id.register) {
            Intent registerIntent = new Intent(Login.this, RegisterActivity.class);
            startActivity(registerIntent);
        }
    }
    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

}